{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 主题一：Python数据与应用--技术知识  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 目标"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **应用目标**\n",
    "    1. **阶段实战：利用输入输出，实现常见的输入查询小程序**\n",
    "    2. **综合实战：信息管理系统的欢迎界面实现**\n",
    "    \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **技能目标**\n",
    "    1. **能编写并运行Python程序**\n",
    "    2. **基本技术应用能力**\n",
    "        - `能使用变量存储各种来源的数据；`\n",
    "        - `能使用标准输出语句实现各种类型的数据输出；`\n",
    "        - `能使用标准输入语句实现各种类型的数据输入；`\n",
    "        - `能使用数据做简单的运算；`\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **知识点目标**\n",
    "    1. **掌握Python开发环境搭建**\n",
    "    \n",
    "        - `Python在Mac OS，Linux/Unix，Window平台下的安装；`\n",
    "        - `python解释器的使用；`\n",
    "        - `了解Python交互式编程（终端与Web端）；`\n",
    "        - `help与dir的使用；`\n",
    "        - `了解pydoc；`\n",
    "        - `了解pyc/pyo文件；`\n",
    "\n",
    "    2. **掌握Python语言结构**\n",
    "        - `Python的目录管理规则；`\n",
    "        - `Python的文件规则；`\n",
    "        - `Python的字规则；`\n",
    "        - `Python的句规则；`\n",
    "        - `Python的段规则；`\n",
    "\n",
    "    3. **掌握Python数据语句的语法**\n",
    "        - `定义数据变量；`\n",
    "        - `访问数据变量；`\n",
    "        - `数据类型与数据值表示；`\n",
    "\n",
    "    4. **掌握Python功能语句的语法**\n",
    "        - `数据类型功能语句；`\n",
    "        - `标准输出语句；`\n",
    "        - `标准输入语句；`\n",
    "\n",
    "    5. **掌握特殊语句**\n",
    "        - `注释语句；`\n",
    "        - `文档语句；`\n",
    "        - `import与from语句；`\n",
    "        - `解释器说明语句；`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python开发环境搭建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python在Mac OS，Linux/Unix，Window平台下的安装；\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. 下载地址\n",
    "\n",
    "    - https://www.python.org\n",
    "    ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2. 平台选择\n",
    "    操作系统安装选择开发环境：截图如下：\n",
    "    >![image.png](attachment:image.png)\n",
    "\n",
    "    - 在【Downloads】菜单选择对应的平台下载，注意选择下载版本，我们选择的是3.6.6版本。（含rc的标识是发布候选版本：Release Candidate）\n",
    "\n",
    "        - 【Source code】 所有平台都可以，需要编译环境，在Linux下安装就下载这个。包含两种压缩格式，我们选择`Gzipped source tarball`压缩格式\n",
    "    \n",
    "        - 【Windows】分成很多种安装形式，还跟Windows系统分成32为与64位，我们选择下载`Windows x86-64 executable installer`。\n",
    "        \n",
    "        - 【Mac OS X】分成64与32位，格式是pkg格式，我们选择`macOS 64-bit installer`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3. Python安装\n",
    "\n",
    "    - Windows与Mac OS X都是二进制执行文件可视化安装，只需要连续点【下一步】就可以完成安装，这里不演示。\n",
    "    \n",
    "    - Linux在官网没有二进制安装文件，就需要编译安装，安装步骤如下：\n",
    "        \n",
    "        - 解压缩tar文件：`tar xvf  Python-3.6.6.tar`，或者在Linux资源管理器可视化解压缩。\n",
    "        \n",
    "        - 进入解压目录，执行'./configure' 用于根据系统环境生成makefile\n",
    "        \n",
    "        - 执行`make`命令进行编译，这个需要一点时间\n",
    "        \n",
    "        - 执行`make install`命令进行安装，安装的目录是默认目录，如果想安装在指定目录，在执行`configure`的时候，指定一个参数即可`--prefix=PREFIX （其中PREFIX用自己的安装目录替代，如果不设置，默认安装在[/usr/local]下）`\n",
    "        \n",
    "        - 根据需要可以设置PATH环境变量，或者设置软连接。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4. Python IDE工具安装\n",
    "    \n",
    "&emsp;&emsp;Python IDE工具有很多，只要能文本编辑即可（Eclipse，PyCharm，VIM，Sublime等），我们选择PyCharm；\n",
    "\n",
    "- PyCharm安装\n",
    "    \n",
    "    - Mac OS X与Windows都是二进制可视化安装；\n",
    "    \n",
    "    - Linux是绿色安装，直接下载解压就可以使用。   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### python解释器的使用；\n",
    "\n",
    "&emsp;&emsp;Python程序与传统的二进制执行程序不一样，Python程序是脚本程序，需要解释器解释执行，这个解释器就是python程序，安装好Python开发环境后，就可以使用这个解释器解释执行所有python程序。\n",
    "演示python解释器的一个python程序（文件名:e01_hello.py）\n",
    "\n",
    "```python\n",
    "    import sys\n",
    "    import warnings\n",
    "\n",
    "    var = 8888\n",
    "    print('演示python解释器')\n",
    "    print(sys.path)\n",
    "    warnings.warn(\"deprecated\", BytesWarning)\n",
    "```\n",
    "- Python的选项（通过Python的选项可以控制解释器的执行）\n",
    "\n",
    "    - -v 选项：输出python执行加载过程。\n",
    "\n",
    "    ```shell\n",
    "    localhost:~ yangqiang$python  -v   e01_hello.py     \n",
    "    \n",
    "    localhost:~ yangqiang$python -v   # 进入交互式编程终端\n",
    "    \n",
    "    ```\n",
    "    - -O / -OO 选项   优化选项/优化并忽略文档字符串。\n",
    "    \n",
    "    ```shell\n",
    "    localhost:~ yangqiang$python -O  hello.py\n",
    "   \n",
    "    ```\n",
    "   \n",
    "    - -c 选项 使用命令行执行python代码。\n",
    "    \n",
    "    ```shell\n",
    "    localhost:~ yangqiang$ python -c 'import sys;print(sys.argv)'  p1=1  p2=hello      \n",
    "    ['-c', 'p1=1', 'p2=hello']\n",
    "    \n",
    "    ```\n",
    "    \n",
    "    - -i 选项  在进入交互式编程之前，先执行-i后紧跟的python脚本。\n",
    "    \n",
    "    ```shell\n",
    "    localhost:T01 yangqiang$ python -i e01_hello.py \n",
    "    \n",
    "    演示python解释器\n",
    "    ['/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']\n",
    "    >>> \n",
    "    ```\n",
    "    \n",
    "    - -W 选项  用来控制警告输出（default，all，ignore，module，once，error）。\n",
    "    \n",
    "    ```shell\n",
    "    localhost:T01 yangqiang$ python -W all e01_hello.py\n",
    "    \n",
    "    演示python解释器\n",
    "    ['/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']\n",
    "    e01_hello.py:6: BytesWarning: deprecated                # 警告信息\n",
    "      warnings.warn(\"deprecated\", BytesWarning)\n",
    "    localhost:T01 yangqiang$ \n",
    "    \n",
    "    ```\n",
    "    \n",
    "    - -m 选项 使用模块方式执行py脚本程序。\n",
    "    ```shell\n",
    "    localhost:T01 yangqiang$ python -m e01_hello\n",
    "    \n",
    "    演示python解释器\n",
    "    ['', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']\n",
    "    localhost:T01 yangqiang$ \n",
    "    ```\n",
    "    \n",
    "&emsp;&emsp;目前暂时不要求对解释器选项做深入掌握（后面使用到的时候，知道有这个知识点）。   \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- python的环境变量\n",
    "\n",
    "    - python运行还依赖一些环境变量（或者被一些环境变量影响）。  \n",
    "    \n",
    "    - 主要的环境变量： \n",
    "        \n",
    "        - PYTHONHOME     # 指定python的安装主目录：默认/usr/local\n",
    "        - PYTHONPATH      # py文件的所有路径\n",
    "    \n",
    "    -  其他环境变量（主要用来控制python的选项，这样避免每次在命令行输入）：\n",
    "        \n",
    "        - PYTHONSTARTUP: 启动脚本，用来做一些python设置\n",
    "        - PYTHONOPTIMIZE：等于-O\n",
    "        - PYTHONDEBUG：等价于-d\n",
    "        - PYTHONDONTWRITEBYTECODE：等价于-B\n",
    "        - PYTHONINSPECT：等价于-i\n",
    "        - PYTHONIOENCODING：指定编码\n",
    "        - PYTHONNOUSERSITE：等价于-s：管理用户site路径\n",
    "        - PYTHONUNBUFFERED：等价于-u\n",
    "        - PYTHONVERBOSE：等价于-v\n",
    "        - PYTHONWARNINGS：等价于-W\n",
    "        - PYTHONHASHSEED：使用随机数做hash散列值计算的种子。\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 使用pyvenv工具创建隔离的运行环境\n",
    "    - 创建工作目录\n",
    "    ```shell\n",
    "    localhost:codes yangqiang$ mkdir PyENV\n",
    "    \n",
    "    localhost:codes yangqiang$ cd PyENV/\n",
    "    ```\n",
    "    - 创建python虚拟环境\n",
    "    ```shell\n",
    "    localhost:PyENV yangqiang$ pyvenv  my_env\n",
    "\n",
    "    ```\n",
    "    - 激活虚拟环境\n",
    "    ```shell\n",
    "    localhost:PyENV yangqiang$ cd my_env/\n",
    "    \n",
    "    localhost:my_env yangqiang$ ls\n",
    "    bin\t\tinclude\t\tlib\t\tpyvenv.cfg\n",
    "    \n",
    "    localhost:my_env yangqiang$ cd bin/\n",
    "\n",
    "    localhost:bin yangqiang$ ls\n",
    "    activate\t\tactivate.fish\t\teasy_install-3.6\tpip3\t\t\tpython\t\t\tpython3.6\n",
    "    activate.csh\t\teasy_install\t\tpip\t\t\tpip3.6\t\t\tpython3\n",
    "\n",
    "    localhost:bin yangqiang$ source activate\n",
    "\n",
    "    ``` \n",
    "    \n",
    "    - 验证虚拟环境\n",
    "    \n",
    "    ```shell\n",
    "        (my_env) localhost:bin yangqiang$ pip list\n",
    "\n",
    "        Package    Version\n",
    "        ---------- -------\n",
    "        pip        10.0.1 \n",
    "        setuptools 39.0.1 \n",
    "        You are using pip version 10.0.1, however version 19.0.3 is available.\n",
    "        You should consider upgrading via the 'pip install --upgrade pip' command.\n",
    "\n",
    "        (my_env) localhost:bin yangqiang$\n",
    "\n",
    "    ```   \n",
    "    可以看见python的安装的模块都没有了，产生了一个新的空白环境。\n",
    "    - 退出虚拟环境\n",
    "    \n",
    "    ```shell\n",
    "        (my_env) localhost:bin yangqiang$ deactivate\n",
    "    ```\n",
    "    - Pycharm下配置\n",
    "        在解释器处配置，选择虚拟环境即可。![image.png](attachment:image.png)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python交互式编程（终端与Web端）；\n",
    "\n",
    "- 在命令行，不执行执行脚本，会直接进入交互式编程状态。\n",
    "\n",
    "\n",
    "- 同时Python提供了一个模块工具实现在Web页面中执行程序（还可以编辑文档）：ipython或者jupyter。       \n",
    "\n",
    "&emsp;&emsp;暂时不掌握，后面使用到的时候，知道有这个知识点。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### help与dir的使用；\n",
    "\n",
    "- help列出帮助文档。\n",
    "\n",
    "    - 命令： `help(sys)`         \n",
    "        **注意：**先引入，在查看帮助\n",
    "        \n",
    "    - 查看目录（包，含：用户的与系统）   \n",
    "    \n",
    "    ```shell\n",
    "    localhost:codes yangqiang$ ls  \n",
    "    T01\tcommon\n",
    "    localhost:codes yangqiang$ python\n",
    "    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 26 2018, 19:50:54) \n",
    "    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin\n",
    "    Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n",
    "    >>> help(T01)\n",
    "    Traceback (most recent call last):\n",
    "      File \"<stdin>\", line 1, in <module>\n",
    "    NameError: name 'T01' is not defined\n",
    "    >>> import T01\n",
    "    >>> help(T01)\n",
    "\n",
    "    >>> \n",
    "    ```\n",
    "    - 查看模块\n",
    "    \n",
    "    ```shell\n",
    "    >>> import T01.e01_hello                # 先引入\n",
    "    \n",
    "    演示python解释器\n",
    "    ['', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']\n",
    "    >>> help(T01.e01_hello)                  # 查看帮助\n",
    "    ```\n",
    "    - 查看类\n",
    "    \n",
    "    ```shell\n",
    "    >>> import threading\n",
    "    >>> help(threading.Thread)\n",
    "    ```\n",
    "    - 查看函数\n",
    "    \n",
    "    ```shell\n",
    "    >>> import math\n",
    "    >>> help(math.sin)\n",
    "    ```\n",
    "\n",
    "- dir查看对象的成员细节。\n",
    "    - dir与help的使用方式一样，只是输出方式不同。\n",
    "    \n",
    "    ```shell\n",
    "    >>> dir(T01)\n",
    "    ['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'e01_hello']\n",
    "    >>> \n",
    "    ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### pydoc模块与pydoc3命令\n",
    "&emsp;&emsp;pydoc是python自带的一个文档生成服务模块，使用pydoc启动一个Web服务器，然后使用浏览器可以很方便的查看类和方法结构。\n",
    "&emsp;&emsp;只要在PYTHONPATH环境变量识别的路径都会自动生成文档。比如：要显示系统与用户模块的帮助：    \n",
    "&emsp;&emsp;使用命令`pydoc3 -h`获取pydoc3的命令帮助。\n",
    "\n",
    "- pydoc有两种执行方式\n",
    "    \n",
    "    - 模块执行\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "        python -m pydoc\n",
    "        \n",
    "    ```\n",
    "    - 执行文件执行\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "        pydoc3\n",
    "        \n",
    "    ```    \n",
    "    \n",
    "- 使用pydoc启动文档服务。 \n",
    "\n",
    "```shell\n",
    "\n",
    "    localhost:codes yangqiang$ ls\n",
    "    \n",
    "    T01\tcommon\n",
    "    \n",
    "    localhost:codes yangqiang$ export PYTHONPATH='./T01'\n",
    "    \n",
    "    localhost:codes yangqiang$ echo $PYTHONPATH\n",
    "    \n",
    "    ./T01\n",
    "    \n",
    "    localhost:codes yangqiang$ python -m pydoc -p 8899\n",
    "    localhost:codes yangqiang$ pydoc3 -p 8899\n",
    "    \n",
    "    Server ready at http://localhost:8899/\n",
    "    Server commands: [b]rowser, [q]uit\n",
    "    server> b\n",
    "    \n",
    "    server> ['', '/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']\n",
    "    \n",
    "```\n",
    "\n",
    "- 在浏览器中查看结果\n",
    "![image.png](attachment:image.png)\n",
    "\n",
    "- pydoc的其他用法 \n",
    "\n",
    "    - 直接查看某个py文件的内容 (与help一样的效果)\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "    localhost:codes yangqiang$ python -m pydoc T01.e01_hello\n",
    "    ```\n",
    "    \n",
    "    - 生成html说明文档\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "    localhost:codes yangqiang$ python -m pydoc -w T01.e01_hello\n",
    "    \n",
    "    演示python解释器\n",
    "    ['', '/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']\n",
    "    wrote T01.e01_hello.html\n",
    "    localhost:codes yangqiang$ \n",
    "    ```\n",
    "    \n",
    "    **注意：**会生成一个文件名是`T01.e01_hello.html`的HTML文件。\n",
    "    \n",
    "    - -k查找模块\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "    yangqiang$ pydoc3 -k hello      # 查找包含hello的模块\n",
    "    ```\n",
    "    \n",
    "\n",
    "&emsp;&emsp;**注意：**具体的可以在标准帮助查看pydoc模块的使用，以及pydoc3工具的使用。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### pyc与pyo文件\n",
    " \n",
    "- pyc文件\n",
    "    \n",
    "    - python编译后的字节码文件，用于提高加载速度与解释速度，因为缺少一个翻译过程（不提高程序运行速度：这个由程序决定）\n",
    "    \n",
    "    - pyc文件的编译：\n",
    "        \n",
    "        - 一般在模块加载的时候，会自动生成pyc文件，然后再加载。\n",
    "        - 手工编译\n",
    "        \n",
    "        ```shell\n",
    "        \n",
    "        python  -m py_compile  e01_hello.py      # 编译指定的文件\n",
    "        python  -m compileall .                         # 编译整个目录\n",
    "        ```\n",
    "        \n",
    "        编译后的文件存放在py文件所在目录下的__pycache__目录中，一般默认文件名：`e01_hello.cpython-36.pyc`\n",
    "        \n",
    "    - pyc文件的执行\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "    localhost:__pycache__ yangqiang$ python d01_query.cpython-36.pyc \n",
    "    \n",
    "    ['/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01/__pycache__', '/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01/__pycache__/T01', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']\n",
    "    localhost:__pycache__ yangqiang$ \n",
    "\n",
    "    ```\n",
    "\n",
    "- pyo文件\n",
    "    \n",
    "    - 与pyc一样都是字节码文件，与pyc的区别是：pyo是优化后的字节码文件，比如：优化（删除）注释的处理等。pyo文件一般比pyc文件要小，加载速度会快。\n",
    "    \n",
    "    - pyo文件的编译，与pyc一样，只需要多增加一个-O选项\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "    python -O  -m py_compile  e01_hello.py \n",
    "    python -OO  -m py_compile  e01_hello.py \n",
    "    \n",
    "    python -O  -m compileall .\n",
    "    python -OO  -m compileall .\n",
    "    ```\n",
    "        \n",
    "    - pyo文件的执行，与pyc一样。\n",
    "    \n",
    "    - **注意：**在python3中，默认优化编译的文件为`e01_hello.cpython-36.opt-1.pyc`（-O）或者`e01_hello.cpython-36.opt-2.pyc`（-OO），一般我们会使用pyo来区分pyc。\n",
    "    \n",
    "- 其他文件（pyd文件）\n",
    "    \n",
    "    - Python格式的动态链接库文件，本质还是dll（lib）或者so（a）文件；\n",
    "    - 在Python中编译pyd文件，需要`Cython`模块，安装指令`pip install Cython`\n",
    "    - 下面是一个例子：\n",
    "        - pyd的业务实现：`e02_pyd.py`\n",
    "        \n",
    "        ```python\n",
    "        \n",
    "            def hello_pyd():\n",
    "            print(\"pyd文件理解，编译与调用\")\n",
    "\n",
    "        ```\n",
    "        - pyd的动态库调用封装：`e02_pyd_ex.py`\n",
    "        \n",
    "        ```python\n",
    "        \n",
    "            from distutils.core import setup\n",
    "            from Cython.Build import cythonize\n",
    "            setup(ext_modules=cythonize('e02_pyd.py'))\n",
    "\n",
    "        ```\n",
    "        - pyd的编译脚本：`e02_pyd.sh`\n",
    "        ```shell\n",
    "        \n",
    "        python e02_pyd_ex.py  build_ext --inplace\n",
    "\n",
    "        ```\n",
    "        - pyd编译生成的文件：（记得安装Cython：pip install Cython）\n",
    "            ![image.png](attachment:image.png)\n",
    "        - pyd的调用：`e02_pyd_call.py`\n",
    "        \n",
    "        ```python\n",
    "\n",
    "            from T01.e02_pyd import hello_pyd\n",
    "\n",
    "            hello_pyd()\n",
    "        ```\n",
    "            - 运行的注意事项：删除`e02_pyd.c`与`e02_pyd.py`, 只留下so文件，可以体会下python调用动态库的酸爽感觉。 \n",
    "            - 在python中，一般使用pyd，而不是使用so扩展名。pyd本质是so文件（windows是dll文件，提示：除动态库，还有一个名词是静态库）   \n",
    "            - 这个文件与本地动态库文件还是有区别，因为使用nm指令无法查看文件的符号表。  \n",
    "\n",
    "- 注意：\n",
    "    \n",
    "    - 可以在python中，使用-B选项，禁止生成pyc与pyo文件。\n",
    "    - 可以在Python代码实现编译，在后面我们会专门讲解。 \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 把python编译成本地文件执行\n",
    "    \n",
    "- pyinstaller的帮助：\n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "        localhost:T01 yangqiang$ pyinstaller -h\n",
    "        \n",
    "        usage: pyinstaller [-h] [-v] [-D] [-F] [--specpath DIR] [-n NAME]\n",
    "                           [--add-data <SRC;DEST or SRC:DEST>]\n",
    "                           [--add-binary <SRC;DEST or SRC:DEST>] [-p DIR]\n",
    "                           [--hidden-import MODULENAME]\n",
    "                           [--additional-hooks-dir HOOKSPATH]\n",
    "                           [--runtime-hook RUNTIME_HOOKS] [--exclude-module EXCLUDES]\n",
    "                           [--key KEY] [-d [{all,imports,bootloader,noarchive}]] [-s]\n",
    "                           [--noupx] [-c] [-w]\n",
    "                           [-i <FILE.ico or FILE.exe,ID or FILE.icns>]\n",
    "                           [--version-file FILE] [-m <FILE or XML>] [-r RESOURCE]\n",
    "                           [--uac-admin] [--uac-uiaccess] [--win-private-assemblies]\n",
    "                           [--win-no-prefer-redirects]\n",
    "                           [--osx-bundle-identifier BUNDLE_IDENTIFIER]\n",
    "                           [--runtime-tmpdir PATH] [--bootloader-ignore-signals]\n",
    "                           [--distpath DIR] [--workpath WORKPATH] [-y]\n",
    "                           [--upx-dir UPX_DIR] [-a] [--clean] [--log-level LEVEL]\n",
    "                           scriptname [scriptname ...]\n",
    "                           ......\n",
    "    ```\n",
    "    \n",
    "- pynstaller使用例子：      \n",
    "    \n",
    "    ```shell\n",
    "    \n",
    "    localhost:T01 yangqiang$ pyinstaller --workpath dd  --distpath oo -i AppIcon.icns  -F -w  e01_hello.py \n",
    "    \n",
    "    70 INFO: PyInstaller: 3.4 \n",
    "    70 INFO: Python: 3.6.6 \n",
    "    78 INFO: Platform: Darwin-16.7.0-x86_64-i386-64bit \n",
    "    79 INFO: wrote /Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01/e01_hello.spec\n",
    "    82 INFO: UPX is not available.\n",
    "    84 INFO: Extending PYTHONPATH with paths\n",
    "    ['/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01',\n",
    "     '/Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01']\n",
    "    84 INFO: checking Analysis\n",
    "    84 INFO: Building Analysis because Analysis-00.toc is non existent\n",
    "    84 INFO: Initializing module dependency graph...\n",
    "    87 INFO: Initializing module graph hooks...\n",
    "    89 INFO: Analyzing base_library.zip ...\n",
    "    3849 INFO: running Analysis Analysis-00.toc\n",
    "    3857 INFO: Caching module hooks...\n",
    "    3863 INFO: Analyzing /Users/yangqiang/Documents/PythonDev/00Python入门基础/codes/T01/e01_hello.py\n",
    "    3867 INFO: Loading module hooks...\n",
    "    3868 INFO: Loading module hook \"hook-encodings.py\"...\n",
    "    3992 INFO: Loading module hook \"hook-pydoc.py\"...\n",
    "    3994 INFO: Loading module hook \"hook-xml.py\"...\n",
    "    4286 INFO: Looking for ctypes DLLs\n",
    "    4286 INFO: Analyzing run-time hooks ...\n",
    "    4293 INFO: Looking for dynamic libraries\n",
    "    4381 INFO: Looking for eggs\n",
    "    4381 INFO: Using Python library /Library/Frameworks/Python.framework/Versions/3.6/Python\n",
    "    4383 INFO: Warnings written to dd/e01_hello/warn-e01_hello.txt\n",
    "    4407 INFO: Graph cross-reference written to dd/e01_hello/xref-e01_hello.html\n",
    "    4415 INFO: checking PYZ\n",
    "    4415 INFO: Building PYZ because PYZ-00.toc is non existent\n",
    "    4416 INFO: Building PYZ (ZlibArchive) dd/e01_hello/PYZ-00.pyz\n",
    "    4734 INFO: Building PYZ (ZlibArchive) dd/e01_hello/PYZ-00.pyz completed successfully.\n",
    "    4739 INFO: checking PKG\n",
    "    4739 INFO: Building PKG because PKG-00.toc is non existent\n",
    "    4739 INFO: Building PKG (CArchive) PKG-00.pkg\n",
    "    7072 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.\n",
    "    7075 INFO: Bootloader /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PyInstaller/bootloader/Darwin-64bit/runw\n",
    "    7075 INFO: checking EXE\n",
    "    7075 INFO: Building EXE because EXE-00.toc is non existent\n",
    "    7075 INFO: Building EXE from EXE-00.toc\n",
    "    7076 INFO: Appending archive to EXE oo/e01_hello\n",
    "    7083 INFO: Fixing EXE for code signing oo/e01_hello\n",
    "    7089 INFO: Building EXE from EXE-00.toc completed successfully.\n",
    "    7092 INFO: checking BUNDLE\n",
    "    7092 INFO: Building BUNDLE because BUNDLE-00.toc is non existent\n",
    "    7092 INFO: Building BUNDLE BUNDLE-00.toc\n",
    "    7104 INFO: moving BUNDLE data files to Resource directory\n",
    "    localhost:T01 yangqiang$ \n",
    "\n",
    "    ```\n",
    "- **说明：**        \n",
    "    - oo是生成的本地执行文件的存放目录\n",
    "    - dd是编译中间文件的存放目录，\n",
    "    - -F控制把所有资源编译生成一个执行文件。 \n",
    "    - -i 指定程序图标（图标只对非控制台应用有效）    \n",
    "    - -w 生成window程序\n",
    "    \n",
    "    下面是在Mac OS X下编译结果（盗用腾讯课堂的图标）：\n",
    "\n",
    "     **注意图标**![image.png](attachment:image.png)\n",
    "\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python语言结构\n",
    "\n",
    "&emsp;&emsp;了解一个语言的结构，从整体上认识一个语言需要学习的语法，以及语法的作用，我认为对掌握一门语言至关重要。 我们可以把语法称为一组规则，不遵循语法规则的下场就是得到一个运行错误：\n",
    "\n",
    "```python\n",
    "\n",
    "    SyntaxError: invalid syntax\n",
    "```\n",
    "\n",
    "- **语言结构大致可以分成几个方面的规则：**      \n",
    "    \n",
    "    - **程序结构规则**\n",
    "        - 目录规则\n",
    "        - 文件规则\n",
    "    \n",
    "    - **字规则**\n",
    "        - 字面字\n",
    "        - 保留字\n",
    "        - 标识字\n",
    "        \n",
    "    - **句规则**\n",
    "        - 数据语句\n",
    "        - 功能语句\n",
    "        - 空语句\n",
    "        \n",
    "    - **块规则**\n",
    "        - 控制块\n",
    "        - 函数块\n",
    "        - 类块\n",
    "        - 异常控制块\n",
    "        - with块\n",
    "        \n",
    "        **学习方法就是：**      \n",
    "            &emsp;&emsp;掌握基本语法后，掌握更多的语句，掌握更多的块，达到熟练的语言应用能力。      \n",
    "        **下面是一个结构图：**\n",
    "        ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python的目录管理规则"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- python程序都是由文件构成，每个文件使用目录管理，这一点与操作系统的文件管理肯定一致。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- python从效率上来讲，把目录分成两个部分管理：\n",
    "    \n",
    "    - 项目所在目录： \n",
    "        - 由python解释器来管理；\n",
    "        - python管理的方式采用环境变量：PYTHONPATH，该环境变量的设置\n",
    "            \n",
    "            - 在系统配置文件设置PYTHONPATH环境变量\n",
    "            - 通过sys.path来设置\n",
    "        - PYTHONPATH决定了python查找搜索py文件的范围。\n",
    "        \n",
    "    - 项目内部的目录： \n",
    "        - 项目内部的目录，也称为：包（package）\n",
    "        - 指明访问那个项目内的目录，使用特殊的语句：import 目录，也称包加载。（包的加载在后面专门解释）\n",
    "        - 项目的目录采用的分隔符与操作系统的分隔符有区别，使用 “ . ” 分隔。比如：`import PyQt5.QtGui`\n",
    "        - python的包目录区分大小写。\n",
    "        - 目录下的内容与帮助，使用help可以查看。\n",
    "        - python交互终端，会默认把当前的路径作为项目路径，PYTHONPATH。\n",
    "        \n",
    "        \n",
    "![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面是通过环境变量来设置Python的搜索路径：\n",
    "![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python的文件规则\n",
    "\n",
    "&emsp;&emsp;所有python代码都是使用文件存放，这就是python文件；\n",
    "\n",
    "- 文件格式\n",
    "    - python代码文件都是文本文件\n",
    "\n",
    "-  文件命名\n",
    "    - 推荐使用py作为扩展名（可以是任何名）\n",
    "    - 文件名只要符合系统要求都支持\n",
    "    ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;由于非英文字符的引入，所有文本文件都存在编码问题，python默认采用UTF-8编码；\n",
    "- 文件的编码\n",
    "    - python独有的编码识别：`# encoding = utf-8` 或者`# -*- coding:utf-8 -*-`，前一种Emacs编辑器不支持；\n",
    "    - 文本文件通用的编码识别：使用文本文件前三个字节标明编码（BOM：byte order mark）。\n",
    "    - 目前很多文本编辑器都支持存储的时候指定使用BOM，比如：`UTF-8 BOM`\n",
    "    ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python的字规则；\n",
    "&emsp;&emsp;键盘上能输入的任何字符都是python文件中的肯能的一部分，但这些字符按照规则构成python程序。构成过程可以表示如下：      \n",
    "&emsp;&emsp;&emsp;&emsp;$ \\text{字符} \\to \\text{字} \\to \\text{句} \\to \\text{块结构} $\n",
    "&emsp;&emsp;\n",
    "\n",
    "- 字：python执行程序首先需要断字，断句，如果语法模糊，python解释器无法断字，断句，程序就无法自行。\n",
    "\n",
    "    - Python的字主要使用空格分开（这是西方的单词规则，与汉字不同），\n",
    "    - 同时还可以使用特殊的字符，比如：. ( )   换行，制表符，+ 运算符等。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 字面值\n",
    "\n",
    "- 字面值：表示值，其表示遵循我们的常识，数值遵循我们数学中接触的常识：\n",
    "    - 字面值的官方帮助：字符串字面值规则在官方文档（2.4. Literals）节\n",
    "    ![image.png](attachment:image.png)\n",
    "    - 字面值必须使用西文字符，除非是字符串中的字（初学者尝尝因为字符是汉字导致不知道的错误，尤其是汉字全角空格，看不见摸不着，还总报错）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 数值表示\n",
    "    - 整数\n",
    "        - 二进制\n",
    "        - 八进制\n",
    "        - 十进制\n",
    "        - 十六进制\n",
    "    ```python\n",
    "\n",
    "        0b01010101\n",
    "        0B01010101\n",
    "\n",
    "        0o7777\n",
    "        0O7777\n",
    "\n",
    "        999999\n",
    "\n",
    "        0xffff\n",
    "        0xFFFFF\n",
    "        0Xffff\n",
    "        0XFFFFF\n",
    "    ```\n",
    "\n",
    "    - 小数\n",
    "        - 普通表示法\n",
    "        - 科学记数法（指数部分必须是整数，只能十进制）\n",
    "    ```python\n",
    "        23.67\n",
    "        34.45e6\n",
    "        4.566E8\n",
    "    ```\n",
    "        - 如果小数，前面的0可以省略：\n",
    "        ```python\n",
    "\n",
    "        .56\n",
    "        .56E10\n",
    "\n",
    "        ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **注意**     \n",
    "    数值型还有负数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nan\n"
     ]
    }
   ],
   "source": [
    "- 20\n",
    "\n",
    "-0o77\n",
    "\n",
    "- 0xff\n",
    "\n",
    "- 45.8e-5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 复数（实部 +/- 虚部 ）\n",
    "    - 实部（与数值表示一样：可以任意进制）\n",
    "    - 虚部（数值j/J，只能十进制）\n",
    "    ```python\n",
    "        3 + 5j\n",
    "        3 + 5J\n",
    "        5J + 3\n",
    "        5j - 3\n",
    "        2.3 + 6.7J\n",
    "        .3 + .7J\n",
    "    ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 逻辑值\n",
    "    - 真：True\n",
    "    - 假：False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字符与字符串表示\n",
    "    - python中字符串有两重用途：表示字符串+表示字节序列\n",
    "    - 单行字符：\n",
    "        - 使用单引号''或者双引号\"\"界定字符与字符串的范围。必须成对出现，不能混用；\n",
    "        - '字符或者字符串'\n",
    "        - \"字符或者字符串\"\n",
    "\n",
    "    - 多行字符串（不可能是字符）：\n",
    "        - 使用三引号（三个三引号构成）：'''字符或者字符串'''\n",
    "        - 说明：引号可以单引号或者双引号。\n",
    "\n",
    "    ```python\n",
    "\n",
    "        'hello'\n",
    "        \"我爱Python，更爱祖国\"\n",
    "        \"\"\"三个\n",
    "        引号\"\"\"\n",
    "        '''\n",
    "        this is a maomaoyu!\n",
    "        春天在我们身边了\n",
    "        '''\n",
    "    ```\n",
    "    - 字符转义\n",
    "        - 冲突字符：\\'  \\\"  \\\\ \n",
    "        - 非可视化字符：见下面附录。   \n",
    "        - 格式化特殊\n",
    "    ```python\n",
    "\n",
    "        'hello\\N{END OF LINE}world'\n",
    "        '\\N{LATIN CAPITAL LETTER GHA}'\n",
    "        '\\N{BOM}'\n",
    "        '\\u8DEF'   # 汉字路\n",
    "    ```\n",
    "    - 字符串前缀\n",
    "        - 原生字符串（不转义），前缀：r与R\n",
    "        - 格式字符串（支持{值}得直接格式化），前缀：f与F\n",
    "        - Unicode字符串（支持UTF-8编码），前缀：u与U\n",
    "        - 混合前缀：\"fr\" | \"Fr\" | \"fR\" | \"FR\" | \"rf\" | \"rF\" | \"Rf\" | \"RF\"\n",
    "\n",
    "        ```python\n",
    "            print(r'\\n')\n",
    "            u'\\u8DEF'   # 内部转换会使用UTF-8\n",
    "            print(F'{20}')\n",
    "            print(F'{20,\"hello\"}')\n",
    "        ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字节串（字节序列）\n",
    "    - 字节串表示方式与字符串一样，唯一的差别是前缀区别，前缀是：b与B\n",
    "    - 字节序列混合前缀：\"b\" | \"B\" | \"br\" | \"Br\" | \"bR\" | \"BR\" | \"rb\" | \"rB\" | \"Rb\" | \"RB\"\n",
    "\n",
    "```python\n",
    "\n",
    "    b'\\xe8\\xb7\\xaf'\n",
    "\n",
    "    print(b'\\xe8\\xb7\\xaf'.decode())\n",
    "    print('\\u8DEF'.encode().decode())\n",
    "    print('路'.encode())\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 附录：\n",
    "    转义字符列表：\n",
    "    \n",
    "Escape Sequence\t|Meaning\n",
    "-|-\n",
    "\\newline\t|Backslash and newline ignored\t \n",
    "\\\\\t|Backslash (\\)\t \n",
    "\\'\t|Single quote (')\t \n",
    "\\\"\t|Double quote (\")\t \n",
    "\\a\t|ASCII Bell (BEL)\t \n",
    "\\b\t|ASCII Backspace (BS)\t \n",
    "\\f\t|ASCII Formfeed (FF)\t \n",
    "\\n\t|ASCII Linefeed (LF)\t \n",
    "\\r\t|ASCII Carriage Return (CR)\t \n",
    "\\t\t|ASCII Horizontal Tab (TAB)\t \n",
    "\\v\t|ASCII Vertical Tab (VT)\t \n",
    "\\ooo\t|Character with octal value ooo\n",
    "\\xhh\t|Character with hex value hh\t\n",
    "\n",
    "    \\a是pc喇叭发声，目前很多主板都不支持了。\\f换页也只能在打印机等设备才有效。 \n",
    "\n",
    "    只能用于字符串中的转义字符：\n",
    "    \n",
    "Escape Sequence\t| Meaning\t\n",
    "-|-\n",
    "\\N{name}\t|Character named name in the Unicode database\t\n",
    "\\uxxxx\t|Character with 16-bit hex value xxxx\t\n",
    "\\Uxxxxxxxx\t|Character with 32-bit hex value xxxxxxxx\t\n",
    "\n",
    "    其中字符名，可以参考如下连接：http://www.unicode.org/Public/9.0.0/ucd/NameAliases.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 空值\n",
    "    - None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 结构体字面值\n",
    "    \n",
    "    - 元组值：( ... , ... , ... )\n",
    "    \n",
    "    - 列表值：\\[ ... , ... , ... \\]\n",
    "    \n",
    "    - 字典值：{ key: value, ... , ... }\n",
    "    \n",
    "    - 集合值：{ ... , ... , ...  }\n",
    "    ```python\n",
    "\n",
    "        (2 + 3j, \"heloo\", 34.67, True, None)\n",
    "        [2 + 3j, \"heloo\", 34.67, True, None]\n",
    "        {2 + 3j, \"heloo\", 34.67, True, None}\n",
    "\n",
    "        {'name':'louis','age':20}\n",
    "\n",
    "    ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 关键字\n",
    "&emsp;&emsp;python解释器专用的字，用来表示一些特殊的含义、值与功能。   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n"
     ]
    }
   ],
   "source": [
    "\n",
    "import keyword\n",
    "print(keyword.kwlist)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 用户标识字\n",
    "&emsp;&emsp;程序员根据需要自己命名的字，比如：变量名，函数名，类名等。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 用户命名规则\n",
    "\n",
    "    - 不能与关键字冲突\n",
    "    - 只能使用三种字符：字母，数字，_\n",
    "    - 只能字母与_开头\n",
    "    - 所以标识字都需要定义后才能使用（标识字的定义由语句完成，后面专门学习各种标识字的定义与使用。）\n",
    "    \n",
    "&emsp;&emsp;**提示：**    \n",
    "&emsp;&emsp;&emsp;&emsp;|- 多字节字符（比如汉字，日文，阿拉伯文，希伯来文）都属于字母（扩展字母）。    \n",
    "\n",
    "```python\n",
    "    \n",
    "    汉字 = 20\n",
    "```\n",
    "\n",
    "&emsp;&emsp;上面标识字不能直接使用。 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 特殊字\n",
    "&emsp;&emsp;我们愿意把运算符+ ，-，\\[ \\] , () , 等划归为特殊字，这些符号都有特殊的作用，比如 \\用来代码续航"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python的句规则；\n",
    "&emsp;&emsp;字构成句，有些字能单独构成行，上面我们举的例子中能看得出。\n",
    "\n",
    "- 句\n",
    "    \n",
    "    - python使用换行，回车来断句。    \n",
    "    \n",
    "    - 如果一行写不下，可以使用续行符，表示物理上的下一行（多行）在python中仍然是一行。\n",
    "        - 续行不能破坏字，就是不能再一个字的中间续行。 (见下面例子)\n",
    "    \n",
    "    - 如果想把多个语句写在一行上，可以使用分号分隔多个语句；\n",
    "\n",
    "- **注意**：\n",
    "    \n",
    "    多个语句写在一行上，使用的是分号，不是逗号（某些时候看起来形式一样，但有本质区别，逗号有其他用途）。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n"
     ]
    }
   ],
   "source": [
    "import keyword\n",
    "print(keyword.\\\n",
    "      kwlist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "30\n",
      "30\n",
      "40\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(None, None)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 20\n",
    "b = 30\n",
    "print(a), print(b)\n",
    "a, b = (a + 10) ,  (b + 10)\n",
    "print(a), print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 块的规则\n",
    "&emsp;&emsp;块由一个或者多个语句构成；一般块的构成：\n",
    "\n",
    "- 块头\n",
    "    - 块头使用冒号表示块头结束；\n",
    "    \n",
    "    - 不同功能的块的块头语法格式不同，后面会详细讲解这个部分的语法；\n",
    "    \n",
    "    - 一般块头都会使用关键字，来说明块的用途；\n",
    "        - if 块：控制\n",
    "        - def 块：定义函数\n",
    "        - try 块：监控代码异常\n",
    "        - class 块：定义类\n",
    "\n",
    "\n",
    "- 块体\n",
    "    - 具有相同缩行字符的语句都认为是同一个块，直到破坏这个规则（低于缩进数）的行出现。\n",
    "    - 在Python中块基本上都可以嵌套。\n",
    "    \n",
    "    \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "if True:\n",
    "    pass\n",
    "else:\n",
    "    pass\n",
    "\n",
    "\n",
    "class A:\n",
    "    class B:\n",
    "        pass\n",
    "    class C:\n",
    "        class D:\n",
    "            def E():\n",
    "                pass\n",
    "\n",
    "\n",
    "def E():\n",
    "    def F():\n",
    "        class G:\n",
    "            pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python数据语句的语法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义数据变量\n",
    "\n",
    "- 数据语句的语法：\n",
    "    \n",
    "    > `变量名 = 数据`\n",
    "    >\n",
    "    > **说明：**数据可以是：字面值，已定义变量，功能语句的结果值\n",
    "    > \n",
    "    > &emsp;&emsp;定义数据变量，实际就是python解释器执行的时候，会申请一块内存空间用来存放数据。 申请空间的时候必须提供数据，只有这样才知道分配多大的空间。（其他语言因为有数据类型，所以在定义变量的时候，是可以不需要提供数据值得）\n",
    "    > \n",
    "    >&emsp;&emsp; 因为计算机的核心是数据运算，所以变量的定义变得非常重要。\n",
    "    \n",
    "- 定义变量的时候，说明数据类型\n",
    "\n",
    "    > &emsp;&emsp;Python是动态语言，内存也是通过计数引用动态管理，数据类型也是动态识别，但了使用或者调用方便，Python3中引入了类型说明，这种说明本身不对变量的数据类型起作用（在赋值过程都是引用，都是指针，没有必要去识别类型，因为变量，随时都可以指向其他类型的数据内存，真正存储数据的内存是存在数据类型），变量的说明语法如下：       \n",
    "    >  \n",
    "    > `变量  : 类型 = 值`\n",
    "    \n",
    "- 释放变量\n",
    "    > del 变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.49999999515173094\n",
      "hell\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "a = 20\n",
    "b = 30 + 20\n",
    "c = a + b + 10\n",
    "d = math.sin(3.14159262 / 6)\n",
    "print(d)\n",
    "\n",
    "e: int = 45\n",
    "\n",
    "e = 'hell'\n",
    "print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 释放变量例子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'a' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-7-6eb0ef49bee6>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0;32mdel\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m: name 'a' is not defined"
     ]
    }
   ],
   "source": [
    "a = 30\n",
    "print(a)\n",
    "del a\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 访问数据变量\n",
    "\n",
    "- 访问数据变量就是直接使用变量（前提是变量已经定义），访问变量可以独立成语句（数据功能语句）；\n",
    "\n",
    "    - 变量可以在需要的数据的任何运算的地方使用。\n",
    "    - 后面会逐步讲解各种语句，基本上都是讲数据怎么计算、处理与使用。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'hello'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "var = 'hello'\n",
    "\n",
    "var    # 可以直接使用，并成为一个语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数据类型与数据值表示\n",
    "\n",
    "&emsp;&emsp;数据在编程非常重要，因为数据有存储大小，定义的内存空间太小数据会溢出，太大浪费空间。所以深入理解数据类型与数据值就是一个程序员的基本素养。  在Python中采用动态管理，不会出现数据溢出的情况，但Python中所有数据都是对象（带结构与功能的数据管理）。从这一点来讲，字面值与变量还是有区别的。  （后面讲内存管理的时候，会更加详细的讲解）\n",
    "&emsp;&emsp;  \n",
    "&emsp;&emsp;下面使用一个例子说明：对象可以有功能处理，字面值没有。  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 20\n",
    "a.bit_length()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-10-4953382c7360>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-10-4953382c7360>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m    20.bit_length()\u001b[0m\n\u001b[0m                ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "20.bit_length()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Python的数据类型\n",
    "    \n",
    "    - int\n",
    "    - float\n",
    "    - complex\n",
    "    - bool\n",
    "    - str\n",
    "    - bytes\n",
    "    - tuple\n",
    "    - list\n",
    "    - dict\n",
    "    - set\n",
    "\n",
    "- **说明：**\n",
    "    - 与其他语言不同的是Python数据类型不是关键字，后面会学习到：因为这些都是类，是内置实现的类，也是用户标识字。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'int'>\n",
      "<class 'float'>\n",
      "<class 'complex'>\n",
      "<class 'bool'>\n",
      "<class 'str'>\n",
      "<class 'bytes'>\n",
      "<class 'tuple'>\n",
      "<class 'list'>\n",
      "<class 'set'>\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "source": [
    "a = 10\n",
    "print(type(a))\n",
    "\n",
    "b = 20.88\n",
    "print(type(b))\n",
    "\n",
    "c = 20 + 5j\n",
    "print(type(c))\n",
    "\n",
    "d = True\n",
    "print(type(d))\n",
    "\n",
    "e = '马哥教育'\n",
    "print(type(e))\n",
    "\n",
    "f = b'abcdef'\n",
    "print(type(f))\n",
    "\n",
    "g = (1, 2, 3)\n",
    "print(type(g))\n",
    "\n",
    "h = [1, 2, 3]\n",
    "print(type(h))\n",
    "\n",
    "i = {1, 2, 3}\n",
    "print(type(i))\n",
    "\n",
    "j = { 'name' : 'Louis', 'age': 20, 30: '个数'}\n",
    "print(type(j))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 查看内置数据类型列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['A', 'E', 'In', 'Out', '_', '_1', '_4', '_8', '_9', '__', '___', '__annotations__', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', '_sh', 'a', 'b', 'c', 'd', 'e', 'exit', 'f', 'g', 'get_ipython', 'h', 'i', 'j', 'keyword', 'math', 'quit', 'var']\n"
     ]
    }
   ],
   "source": [
    "print(dir())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# print(dir(__builtin__))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# print(dir(__builtins__))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 查看数据类型的帮助"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# help(set)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 带格式化的字符串\n",
    "    - ' %格式' % 数据\n",
    "    - F' {变量} '"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据20\n",
      "数据20\n"
     ]
    }
   ],
   "source": [
    "print('数据%d' % 20 )\n",
    "a = 20\n",
    "print(F'数据{a}' )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python功能语句的语法\n",
    "&emsp;&emsp;功能语句主要是用来做数据计算、处理等。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数据类型功能语句\n",
    "\n",
    "&emsp;&emsp;数据类型功能语句，主要是数据类型转换语句（后面会理解到本质是函数调用），这里我们所有的知识点都以语句的形式呈现：   \n",
    "\n",
    "- 进制转换 (非10进制都是字符串表示)\n",
    "    - bin：转换为二进制\n",
    "    - oct：转换为八进制\n",
    "    - hex：转换为十六进制\n",
    "    - int：转换为十进制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n",
      "0b11111100011\n",
      "0o3743\n",
      "0x7e3\n",
      "10\n",
      "63\n",
      "70\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "r = bin(2019)\n",
    "print(type(r))\n",
    "print(r)\n",
    "r = oct(2019)\n",
    "print(r)\n",
    "r = hex(2019)\n",
    "print(r)\n",
    "r = int('1010', 2)\n",
    "print(r)\n",
    "\n",
    "r = int('77', 8)\n",
    "print(r)\n",
    "r = int('77', 9)\n",
    "print(r)\n",
    "r = int('0b1010', 0)     # 字符串中包含进制格式，这需要指定为0\n",
    "print(r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 类型间转换（只限于：int，float，bool，str之间，对结构数据complex，bytes，list，tuple，dict，set暂时不考虑）\n",
    "    主要是字符串与数值类型之间的转换比较常用\n",
    "    - int\n",
    "    - float\n",
    "    - bool\n",
    "    - str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "123\n",
      "20.88\n",
      "True\n",
      "888\n",
      "True\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "r = int('123')\n",
    "print(r)\n",
    "r = float('20.88')\n",
    "print(r)\n",
    "r = bool('True')\n",
    "print(r)\n",
    "\n",
    "r = str(888)\n",
    "print(r)\n",
    "\n",
    "r = bool(888)\n",
    "print(r)\n",
    "\n",
    "r = int(True)\n",
    "print(r)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字符与ASCII码的转换\n",
    "    - chr\n",
    "    - ord\n",
    "    - ascii"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A\n",
      "字\n",
      "'a\\u6c49\\u5b57'\n",
      "97\n",
      "24069\n"
     ]
    }
   ],
   "source": [
    "r = chr(65)\n",
    "print(r)\n",
    "r = chr(0x5b57)\n",
    "print(r)\n",
    "\n",
    "r = ascii('a汉字')     # 非ASCII码字符转换为\\u转义字符（unicode码）支持字符串\n",
    "print(r)\n",
    "\n",
    "r = ord('a')     # 只能一个字符\n",
    "print(r)\n",
    "\n",
    "r = ord('帅')     # 只能一个字符\n",
    "print(r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字符串与字节序列的转换\n",
    "    - bytes\n",
    "    - str\n",
    "    - 还可以使用上面bytes与str的对象函数实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'abcs\\xe6\\xb1\\x89\\xe5\\xad\\x97'\n",
      "abcs汉字\n"
     ]
    }
   ],
   "source": [
    "r = bytes('abcs汉字', 'utf-8')\n",
    "print(r)\n",
    "\n",
    "r = str(b'abcs\\xe6\\xb1\\x89\\xe5\\xad\\x97', 'utf-8')\n",
    "print(r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 整数到字节序列之间的转换\n",
    "\n",
    "    - int.to_bytes()\n",
    "    \n",
    "    - int.from_bytes()\n",
    "    \n",
    "    - 使用位运算\n",
    "    \n",
    "    - 使用struct"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'\\x03x'\n",
      "b'x\\x03'\n",
      "0x378\n",
      "888\n"
     ]
    }
   ],
   "source": [
    "a = 888\n",
    "r = a.to_bytes(2,'big')\n",
    "print(r)\n",
    "r = a.to_bytes(2,'little')\n",
    "print(r)\n",
    "\n",
    "r = hex(a)\n",
    "print(r)\n",
    "\n",
    "r = int.from_bytes(b'\\x03x','big')\n",
    "print(r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 提示：\n",
    "    - 上面代码说明Python采用的字节序是大端字节序（Big-Endian）,一般字节序分成两种\n",
    "        - Big-Endian: 低地址存放高位\n",
    "        - Little-Endian: 低地址存放低位"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 特殊的浮点数(\"Infinity\" | \"inf\"  /  \"nan\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nan\n",
      "inf\n",
      "<class 'float'>\n"
     ]
    }
   ],
   "source": [
    "type(float('NaN'))\n",
    "\n",
    "print(float('NaN'))\n",
    "# nan不能直接使用\n",
    "print(float('inf'))\n",
    "print(type(float('Inf')))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fv = float('nan')\n",
    "import math\n",
    "math.isnan(fv)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 标准输出语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 格式\n",
    "    ```python\n",
    "    print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
    "\n",
    "    ```\n",
    "\n",
    "- 说明\n",
    "    \n",
    "    - value ：输出的数据，可以使用逗号分隔，输出多个数据。\n",
    "    \n",
    "        - 可以输出字面值，变量，以及其他运算输出值；\n",
    "    \n",
    "    - sep ：指定每个值输出之间的间隔。\n",
    "    \n",
    "        - 格式：sep=字符串，默认是空格；\n",
    "    \n",
    "    - end ：指输出结束后的结束字符。\n",
    "        - 格式：end = \n",
    "    \n",
    "    - file ：输出目标，默认是标准输出设备。\n",
    "    \n",
    "    - flush ：强制数据从缓冲刷新到输出目标。（在输出不马上可见的情况下，可以使用该选项，一般缓冲满了才会刷新数据到目标）\n",
    "    \n",
    "    上述数据都是可选的。每个项之间使用逗号分隔。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 例子1\n",
    "    \n",
    "    - 输出值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "888\n",
      "20 True 34.89 5.6e-06 (3+5j) hello [1, 2, 3, 4] {1: 2, 3: 'louis', 'name': 'Jack'}\n",
      "30\n",
      "60 '\\U0001f601'\n"
     ]
    }
   ],
   "source": [
    "print()   # 输出空行\n",
    "print(888)    # 输出一个值\n",
    "print( 20,True, 34.89, 5.6e-6, 3+5j, 'hello', [1,2,3,4], {1:2, 3:'louis', 'name': 'Jack'})  # 输出多个值\n",
    "\n",
    "a = 30\n",
    "print( a )\n",
    "print( a + 30 , ascii('😁'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 例子2\n",
    "    - 输出值之间使用指定字符分隔"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20:30:40\n",
      "20😁30😁40\n",
      "20😁30😁40\n"
     ]
    }
   ],
   "source": [
    "print(20, 30, 40, sep=':')  \n",
    "print(20, 30, 40, sep='\\U0001f601')\n",
    "print(20, 30, 40, sep='😁')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 例子3：\n",
    "    - 指定结束输出字符（默认是回车，如果不想回车，可以通过这这个选项修改）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2030结束\n",
      "20😁30😁结束\n"
     ]
    }
   ],
   "source": [
    "print(20, sep=':' , end='')      # sep对输出值只有一个的情况没有意义\n",
    "print(30, end='')\n",
    "print('结束')\n",
    "\n",
    "print(20, sep=':' , end='😁')      # sep对输出值只有一个的情况没有意义\n",
    "print(30, end='😁')\n",
    "print('结束')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 例子4：\n",
    "    - 使用file，输出数据文件（默认是输出到sys.stdout：标准输出设备（显示器终端）），也可以输出到网络设备的。\n",
    "    - 文件必须是一个打开的字符设备文件；（打开的字符设备文件通常使用一个2字节整数表示）。\n",
    "        - 0 代码标准输入设备；\n",
    "        - 1 表示标准输出设备；\n",
    "        - 2 表示标准错误设备；\n",
    "    - 这种标准设备打开使用\n",
    "        - fdopen打开\n",
    "        ```python\n",
    "            fdopen(代表设备的整数，打开方式，缓冲大小)\n",
    "        ```\n",
    "        其中打开方式与open一样。\n",
    "    - 得到文件中代表设备的整数\n",
    "        使用fileno()\n",
    "        \n",
    "    - 关于文件的一些知识，在后面文件的相关部分会做更加细致的讲解。\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "f = open('a.txt', 'w')\n",
    "print('hello', file=f)\n",
    "print(20,file=f)\n",
    "print(True,file=f,flush=True)\n",
    "print(20, sep=':' , end='😁',file=f)  \n",
    "print(file=f)\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "ename": "OSError",
     "evalue": "[Errno 9] Bad file descriptor",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mOSError\u001b[0m                                   Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-27-5771c1df2719>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0mf1\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfdopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'w'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1024\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'hello'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfile\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mf1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mflush\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m   \u001b[0;31m# 不使用flush，输出慢与下面语句\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      6\u001b[0m \u001b[0mf\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'py.png'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'r'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mOSError\u001b[0m: [Errno 9] Bad file descriptor"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "f1 = os.fdopen(1, 'w', 1024)\n",
    "print('hello', file=f1, flush=True)   # 不使用flush，输出慢与下面语句\n",
    "\n",
    "f = open('py.png', 'r')\n",
    "print(f.fileno())\n",
    "\n",
    "# 这个代码需要在终端下执行，才有效果。因为这里的执行环境没有终端"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 标准输入语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 格式：\n",
    "    ```python\n",
    "    input(prompt=None, /)\n",
    "    ```\n",
    "\n",
    "- 说明：\n",
    "    \n",
    "    - prompt 表示输入前输出的输入提示字符串。\n",
    "    \n",
    "    - 数据项是可选的\n",
    "    \n",
    "    - / 表示/之前的项，都不允许使用prompt='提示'格式，而是直接使用提示字符串'提示'。\n",
    "    \n",
    "    - /的中语法是Cython中存在，在Python中目前还没有实现这种语法，但文档中在使用。 \n",
    "    \n",
    "    - 该语法的解释的出处：https://www.python.org/dev/peps/pep-0457/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 例子1：\n",
    "    - 没有提示的输入："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "45\n",
      "45\n"
     ]
    }
   ],
   "source": [
    "a = input()\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 例子2\n",
    "    - 有提示的输入："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入：56\n",
      "56\n"
     ]
    }
   ],
   "source": [
    "a = input('请输入：')\n",
    "print(a)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 注意：\n",
    "    - 下面代码在当前环境运行没有问题，但在Python中执行存在问题：\n",
    "    ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;&emsp;&emsp;&emsp;在交互式编程下的运行结果：\n",
    "![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入：67\n",
      "67\n"
     ]
    }
   ],
   "source": [
    "b = input(prompt='请输入：')\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 在类Unix内核系统下输入输出中使用转义序列"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 在终端使用（转义序列与Python，是系统终端支持的一种输出格式，我们这儿引入是为了让程序有趣）\n",
    "    ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字符控制-颜色转义序列\n",
    "    \n",
    "    - 1、终端中的颜色由ANSI转义码控制。ANSI转义码使用CSI（控制序列指示器）开头。\n",
    "    - 2、格式：\\^\\[\\[控制码m，其中\\^\\[\\[使用Ctrl+V+ESC可以输入。\"\\033\\[控制码m\"\n",
    "    - 3、多个控制码使用；分割：^[[控制码；控制码m\n",
    "    - 4、颜色控制码格式：必须两位，而且只能是3与4开头，3表示前景色，4表示背景色。颜色表如下：\n",
    "         - 30      　    设置黑色前景\n",
    "         - 31   　       设置红色前景\n",
    "         - 32   　       设置绿色前景\n",
    "         - 33   　       设置黄色前景\n",
    "         - 34   　       设置蓝色前景\n",
    "         - 35    　      设置紫色前景\n",
    "         - 36     　     设置青色前景\n",
    "         - 37    　      设置白色(灰色)前景\n",
    "         - 38      　    在缺省的前景颜色上设置下划线\n",
    "         - 39      　    在缺省的前景颜色上关闭下划线\n",
    "         - 40      　    设置黑色背景\n",
    "         - 41      　    设置红色背景\n",
    "         - 42     　     设置绿色背景\n",
    "         - 43     　     设置黄色背景\n",
    "         - 44     　     设置蓝色背景\n",
    "         - 45     　     设置紫色背景\n",
    "         - 46     　     设置青色背景\n",
    "         - 47      　    设置白色(灰色)背景\n",
    "         - 49      　    设置缺省黑色背景"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字符控制-格式转义序列\n",
    "    - 使用格式（与上面一样, 如果与上面混用，使用分号分隔）：\"\\033\\[控制码m\"\n",
    "    - 0      　     重新设置属性到缺省设置\n",
    "    - 1     　      设置粗体\n",
    "    - 2     　      设置一半亮度(模拟彩色显示器的颜色)\n",
    "    - 4     　      设置下划线(模拟彩色显示器的颜色)\n",
    "    - 5     　      设置闪烁\n",
    "    - 7     　      设置反向图象\n",
    "    - 8    　       隐藏输出 \n",
    "    - 22    　      设置一般密度\n",
    "    - 24    　      关闭下划线\n",
    "    - 25     　     关闭闪烁\n",
    "    - 27     　     关闭反向图象\n",
    "    \n",
    "        ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 其他终端操作转义序列   \n",
    "    - \\033\\[nA    光标上移n行 \n",
    "    - \\033\\[nB    光标下移n行 \n",
    "    - \\033\\[nC    光标右移n列 \n",
    "    - \\033\\[nD    光标左移n列\n",
    "    - \\033\\[y;xH  设置光标位置 \n",
    "    - \\033\\[2J     清屏 \n",
    "    - \\033\\[K     清除从光标到行尾的内容 \n",
    "    - \\033\\[s      保存光标位置 \n",
    "    - \\033\\[u      恢复光标位置 \n",
    "    - \\033\\[?25l   隐藏光标 \n",
    "    - \\033\\[?25h 显示光标"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 还可以设置终端的标题栏标题\n",
    "    ```python\n",
    "\n",
    "        title = F'\\033]0;{\"标题字符串\"}\\007'\n",
    "    \n",
    "    ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 使用转义序列输出的例子：\n",
    "    - 清屏，在屏幕正中输出一个欢迎字样。\n",
    "    - 使用输入使屏幕暂停。\n",
    "    - 效果如下：\n",
    "        ![image.png](attachment:image.png)\n",
    "    - 代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-1-b125ec47ddb4>, line 12)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-1-b125ec47ddb4>\"\u001b[1;36m, line \u001b[1;32m12\u001b[0m\n\u001b[1;33m    pos = F'\\033[{y};{x}H'\u001b[0m\n\u001b[1;37m                         ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# coding = utf-8\n",
    "\n",
    "# 定义数据\n",
    "x = 30\n",
    "y = 12\n",
    "str_title = 'XXX管理系统'\n",
    "\n",
    "\n",
    "clear = '\\033[2J'\n",
    "color = '\\033[32;40m'\n",
    "restore = '\\033[0m'\n",
    "pos = F'\\033[{y};{x}H'\n",
    "title = F'\\033]0;{str_title}\\007'\n",
    "\n",
    "print(title,end='')\n",
    "print(clear,end='')\n",
    "print(color,end='')\n",
    "print(pos, end='')\n",
    "print('欢迎来到Python的世界',end='')\n",
    "print(restore,end='')\n",
    "\n",
    "# 等待输入，然后结束\n",
    "print('\\033[?25l',end='')  # 隐藏光标\n",
    "print('\\033[8m',end='')  # 隐藏输出(等价于禁止回显)\n",
    "print(F'\\033[{22};{38}H', end='') # 输入位置\n",
    "input()\n",
    "print('\\033[?25h',end='')   # 显示光标\n",
    "print(restore, end='')   # 恢复文本属性\n",
    "print(clear, end='')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数学运算语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 运算来自数学，实际上计算机中的运算种类比数学更加多，范围更加广。\n",
    "\n",
    "- 计算语句的语法一般都遵循如下规则（某些特殊运算语法有差异）\n",
    "\n",
    "```\n",
    "    数据值   op    数据值\n",
    "\n",
    "```\n",
    "\n",
    "- 运算语句一般都有运算结果，成为返回值，可以定义变量存储：\n",
    "\n",
    "```\n",
    "    变量 = 数据值   op    数据值\n",
    "```\n",
    "\n",
    "- 说明：\n",
    "    - 数据值可以是字面值，变量，或者功能语句的返回数据值（包含其他数学运算语句的结果）\n",
    "    - 如果变量存在，则变量表示新的值。\n",
    "    - 如果变量不存在，则定义新的变量。\n",
    "\n",
    "- 从幼儿园以来获取的运算符号有：\n",
    "    \n",
    "    - 加减法：+  - \n",
    "    - 乘除法： *   /（代替了我们认知的那个符号，因为键盘没有我们小时候认识的那个符号）  \n",
    "    - //整除  （小学的学习内容，在Python中使用使用双斜杠表示）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "56\n",
      "76\n"
     ]
    }
   ],
   "source": [
    "20 + 30\n",
    "\n",
    "a = 20\n",
    "\n",
    "a + 30\n",
    "\n",
    "a + a\n",
    "\n",
    "a + 30 + 30\n",
    "\n",
    "b = a + 20 + 30\n",
    "\n",
    "30 / 20\n",
    "\n",
    "30 // 20\n",
    "\n",
    "-20\n",
    "\n",
    "c = 20 + int(input())\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 使用前面学习的语句，实现一个加法器\n",
    "    效果如下：\n",
    "    ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b]0;{ \"马哥牌计算器\" }\u0007\u001b[2J\u001b[32;40m\u001b[0;0H\u001b[6;25H┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\u001b[7;25H┃                           ┃\u001b[8;25H┃                           ┃\u001b[9;25H┃                           ┃\u001b[10;25H┃                           ┃\u001b[11;25H┃                           ┃\u001b[12;25H┃                           ┃\u001b[13;25H┃                           ┃\u001b[14;25H┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\u001b[8;32H输入被加数：12*10\n",
      "\u001b[10;32H  输入加数：10\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "invalid literal for int() with base 10: '12*10'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-4-f24456dd0349>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m     30\u001b[0m \u001b[1;31m# 输出计算结果\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     31\u001b[0m \u001b[1;31m# 数据转换\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 32\u001b[1;33m \u001b[0mnum_a\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnum_a\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     33\u001b[0m \u001b[0mnum_b\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnum_b\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     34\u001b[0m \u001b[1;31m# 设置输出位置\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: '12*10'"
     ]
    }
   ],
   "source": [
    "# coding = utf-8\n",
    "\n",
    "# 指标符号\n",
    "# ┏━┳━┓\n",
    "# ┃ ┃ ┃\n",
    "# ┣━╋━┫\n",
    "# ┃ ┃ ┃\n",
    "# ┗━┻━┛\n",
    "\n",
    "print(F'\\033]0;{ \"马哥牌计算器\" }\\007', end='')\n",
    "# 用户交互界面 UI\n",
    "print('\\033[2J', end='')   # 清屏\n",
    "print('\\033[32;40m', end='')\n",
    "print('\\033[0;0H', end='')\n",
    "print('\\033[6;25H┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┓', end='')\n",
    "print('\\033[7;25H┃                           ┃', end='')\n",
    "print('\\033[8;25H┃                           ┃', end='')\n",
    "print('\\033[9;25H┃                           ┃', end='')\n",
    "print('\\033[10;25H┃                           ┃', end='')\n",
    "print('\\033[11;25H┃                           ┃', end='')\n",
    "print('\\033[12;25H┃                           ┃', end='')\n",
    "print('\\033[13;25H┃                           ┃', end='')\n",
    "print('\\033[14;25H┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛', end='')\n",
    "# 输入计算因子\n",
    "# 设置输入位置\n",
    "print('\\033[8;32H', end='')\n",
    "num_a = input('输入被加数：')\n",
    "print('\\033[10;32H', end='')\n",
    "num_b = input('  输入加数：')\n",
    "# 输出计算结果\n",
    "# 数据转换\n",
    "num_a = int(num_a)\n",
    "num_b = int(num_b)\n",
    "# 设置输出位置\n",
    "print('\\033[12;32H', end='')\n",
    "print('计算结果是：\\033[31;1;5m{ num_a + num_b }')\n",
    "\n",
    "\n",
    "# 等待输入，然后结束\n",
    "print('\\033[0m', end='')   # 恢复文本属性\n",
    "print('\\033[?25l', end='')  # 隐藏光标\n",
    "print('\\033[8m',end='')  # 隐藏输出(等价于禁止回显)\n",
    "print(F'\\033[{22};{38}H', end='') # 输入位置\n",
    "input()\n",
    "print('\\033[?25h', end='')   # 显示光标\n",
    "print('\\033[0m', end='')   # 恢复文本属性\n",
    "print('\\033[2J', end='')\n",
    "print('\\033[0;0H', end='')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 其他运算语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 列表与元组中元素访问\n",
    "    - 访问语法：`列表[ 位置 ]`\n",
    "    - 赋值语法：`列表[ 位置 ] = 值`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = (1,2,3,4,5)\n",
    "b = [1,2,3,4,5]\n",
    "a[0]\n",
    "b[2]\n",
    "b[2] = 45\n",
    "b[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 字典访问\n",
    "    - 访问语法：`字典 [ key ]`\n",
    "    - 修改与添加语法：`字典 [ key ] = 值`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "30"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = {\"name\":'赵德柱', 'age':20}\n",
    "d['name']\n",
    "d['age'] = 30\n",
    "d['age']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 特殊语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 注释语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 单行注释\n",
    "    \n",
    "    - 语法： # 注释内容\n",
    "    - 说明： # 与注释内容之间最好空一个空格，这不是必须的；\n",
    "                 注释的内容。就不再被解释器执行，但用来说明程序。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 多行注释\n",
    "\n",
    "    - 在官方文档，只提供了单行注释的说明，没有提到多行注释，在Python中不存在多行注释。\n",
    "    \n",
    "    - 注意：很多人把''' 多行字符串 '''与\"\"\" 多行字符串 \"\"\" 当成多行注释，这是不太严谨的，因为严格意义上是字符串构成的语句，这些语句创建匿名变量，会消耗程序的运行效率。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 文档注释\n",
    "    - 文档注释就是最终使用help能查询到的帮助文档 。\n",
    "    \n",
    "    - 严谨的文档注释使用的是\"\"\"多行文档注释\"\"\"。\n",
    "    \n",
    "    - 目前文档工具也宽松支持其他几种文档注释：'单行文档注释'，\"单行文档注释\"，'''多行文档注释'''\n",
    "    \n",
    "    - 文档注释只有在特定的位置使用（每个块的最前面，除了注释，其他都不能存在，否则就不是文档注释了）。\n",
    "        - 模块注释（文件注释）\n",
    "        - 类块注释\n",
    "        - 函数块注释\n",
    "        \n",
    "    - 说明：没有数据变量注释。\n",
    "\n",
    "- 补充：\n",
    "    - 重新加载模块\n",
    "    ```python\n",
    "         from imp import reload \n",
    "         reload(模块名)\n",
    "    ```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# coding = utf-8\n",
    "\n",
    "# 注释一\n",
    "'注释二'\n",
    "# \"注释三\"\n",
    "# '''注释四'''\n",
    "\"\"\"注释六\"\"\"\n",
    "\"\"\"注释七\"\"\"\n",
    "a = 45\n",
    "\"\"\"注释七\"\"\"   # 这个不是注释，是一个语句\n",
    "\n",
    "\n",
    "def func():\n",
    "    '函数注释'\n",
    "    '函数注释'\n",
    "    pass\n",
    "\n",
    "\n",
    "class ClsA(object):\n",
    "    '类注释'\n",
    "    \"\"\"这个已经不是文档注释了\"\"\"\n",
    "    aa = 20\n",
    "    b2 = 'Hell0'\n",
    "    def meth(self):\n",
    "        '''函数'''\n",
    "        pass\n",
    "\n",
    "    @property\n",
    "    def a(self):\n",
    "        '''注释一'''\n",
    "        return self.aa\n",
    "\n",
    "    @a.setter\n",
    "    def a(self, v):\n",
    "        '''注释二'''\n",
    "        self.aa = v\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 查看注释：\n",
    "    - help（模块名）   # 记得import指定模块\n",
    "    >![image.png](attachment:image.png)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 文档字符串的类型\n",
    "    - 不能使用F格式字符串。\n",
    "    - 不能使用b字节流字符串。\n",
    "    \n",
    "    - 可以使用r。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 包（目录）的注释\n",
    "    - 使用 \\_\\_init\\_\\_.py文件即可。在\\_\\_init\\_\\_.py文件中描述\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- \\_\\_init\\_\\_.py文件\n",
    "\n",
    "    - 该文件主要服务于包，与普通模块文件的编程是一样的。 \n",
    "    - 使用该文件下的类，函数，不需要import 模块。\n",
    "    ![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;使用方式\n",
    "    \n",
    "    - import  包路径    （其中包路径必须在PYTHONPATH环境变量指定的范围）\n",
    "    - help(包路径)\n",
    "    \n",
    ">![image.png](attachment:image.png)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 文档编码语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 用途：\n",
    "    - 本质是一个注释；\n",
    "    - 用来告诉解释器python代码使用的编码\n",
    "    - 这个编码必须与python代码保存时的编码一致，目前编辑器都基本上使用UTF-8编码保存（Window下面会有一些例外）。\n",
    "    \n",
    "- 语法规则\n",
    "\n",
    "    - 必须是第一行，或者第二行\n",
    "    - 官方语法：`coding[=:]\\s*([-\\w.]+)`\n",
    "        - ：`\\s*`表示匹配任意的空格\n",
    "        - ：`\\w`表示匹配字母或数字或下划线或汉字 等价于` [A-Za-z0-9_ ] `。\n",
    "        - 例子： coding= UTF-8\n",
    "        - 例子：coding: UTF-8\n",
    "    - 其他官方的语法：\n",
    "        - GNU Emacs：`# -*- coding: <encoding-name> -*-`\n",
    "        - Bram Moolenaar’s VIM：`# vim:fileencoding=<encoding-name>`\n",
    "        - 使用BOM（就是文档的前面三个字节专门用来标注编码：`byte-order mark (b'\\xef\\xbb\\xbf')` ）\n",
    "\n",
    "- 说明\n",
    "    - 如果不指定，则默认使用UTF-8 ，不过目前大部分编辑器自动使用UTF-8编码。\n",
    "    - PyCharm可以在菜单：【File】$ \\to $【File Encoding】指定"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### import与from语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 用途：\n",
    "    - import语句是用来加载需要使用的模块（会执行）\n",
    "\n",
    "- 语法一：(指定访问路径)\n",
    "    - import  包.包\n",
    "    - import  包.  ....  . 模块\n",
    "    \n",
    "    - 使用：   包.  ....  . 模块.类（或者函数）\n",
    "    - 使用：   包.  ....  . 包.类（或者函数）\n",
    "    >![image.png](attachment:image.png)\n",
    "\n",
    "- 使用的时候，需要前缀包路径与模块名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 语法二：（从指定路径import）\n",
    "    - from  包   import  类（或者函数，或者数据）\n",
    "    \n",
    "    - 使用：直接使用\n",
    "    >![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 语法三：\n",
    "    - import ...  as  别名  \n",
    "        - 对import路径指定别名\n",
    "        \n",
    "    - from  .... import 类    as 别名\n",
    "        - 对引入的类与函数指定别名\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 注意：\n",
    "    只有引入的包，模块与类才能使用。\n",
    "    >![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 解释器说明语句"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 解释器说明语句是脚本语言的特征，一般在支持不同解释器的操作系统上支撑。\n",
    "- 语法：\n",
    "    - `#!解释器程序（包含路径）`   \n",
    "    ```python\n",
    "    #!/usr/bin/python\n",
    "    # coding: utf-8\n",
    "    \n",
    "    ```\n",
    "    - 也可以使用系统所搜方式查找解释器\n",
    "    ```python\n",
    "    #!/usr/bin/env python\n",
    "    # coding: utf-8\n",
    "    ```\n",
    "    - 注意：\n",
    "        必须放在python的第一行。\n",
    "        \n",
    "- 使用：\n",
    "    指定解释器的python程序，就可以像脚本程序一样运行\n",
    "    >![image.png](attachment:image.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 阶段应用实战"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 任务描述\n",
    "    - 输入学生信息，并显示输入记录\n",
    "        - 姓名\n",
    "        - 年龄\n",
    "        - 出生年月\n",
    "        - 身高\n",
    "    \n",
    "- 相关技术点：\n",
    "    - 变量\n",
    "    - 类型转换\n",
    "    - 输入\n",
    "    - 输出\n",
    "    - 操作系统的转义序列"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 综合应用实战"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 任务描述：\n",
    "    - 输入上市公司的公司代码，并当前交易信息。\n",
    "- 打包成本地执行文件：\n",
    "    - 打包成控制台程序 ：`pyinstaller -F p01_demo_query.py`\n",
    "    - 运行结果\n",
    "    >![image.png](attachment:image.png)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 代码\n",
    "\n",
    "```python\n",
    "# coding = utf-8\n",
    "import tushare as ts\n",
    "\n",
    "# 定义数据\n",
    "x = 30\n",
    "y = 6\n",
    "str_title = '股票交易查询'\n",
    "\n",
    "\n",
    "clear = '\\033[2J'\n",
    "color = '\\033[32;40m'\n",
    "restore = '\\033[0m'\n",
    "pos = F'\\033[{y};{x}H'\n",
    "title = F'\\033]0;{str_title}\\007'\n",
    "print(title, end='')\n",
    "print(clear, end='')\n",
    "# print(color, end='')\n",
    "print(pos, end='')\n",
    "str_code = input('输入公司代码：')\n",
    "# 查询数据\n",
    "data = ts.get_realtime_quotes(str_code)\n",
    "# 获得股票交易信息\n",
    "# '''\n",
    "# 0：name，股票名字\n",
    "# 1：open，今日开盘价\n",
    "# 3：price，当前价格\n",
    "# 4：high，今日最高价\n",
    "# 5：low，今日最低价\n",
    "# 8：volume，成交量 maybe you need do volume/100\n",
    "# 9：amount，成交金额（元 CNY）\n",
    "# '''\n",
    "\n",
    "# 名字\n",
    "stock_name = data.loc[0]['name']\n",
    "stock_open = float(data.loc[0]['open'])\n",
    "stock_price = float(data.loc[0]['price'])\n",
    "stock_high = float(data.loc[0]['high'])\n",
    "stock_low = float(data.loc[0]['low'])\n",
    "stock_volume = float(data.loc[0]['volume'])\n",
    "stock_amount = float(data.loc[0]['amount'])\n",
    "print(F'\\033[{7};{30}H{\"--------------------\"}', end='')\n",
    "print(F'\\033[{9};{30}H{\"股票名字\"}：\\033[{9};{42}H{ stock_name }')\n",
    "print(F'\\033[{10};{30}H{\"今日开盘价\"}：\\033[{10};{42}H{ stock_open }')\n",
    "print(F'\\033[{11};{30}H{\"当前价格\"}：\\033[{11};{42}H{ stock_price }')\n",
    "print(F'\\033[{12};{30}H{\"今日最高价\"}：\\033[{12};{42}H{ stock_high }')\n",
    "print(F'\\033[{13};{30}H{\"今日最低价\"}：\\033[{13};{42}H{ stock_low }')\n",
    "print(F'\\033[{14};{30}H{\"成交量\"}：\\033[{14};{42}H{ stock_volume/100 }')\n",
    "print(F'\\033[{15};{30}H{\"成交金额\"}：\\033[{15};{42}H{ stock_amount }')\n",
    "# 输出\n",
    "\n",
    "\n",
    "print(restore, end='')\n",
    "# 等待输入，然后结束\n",
    "print('\\033[?25l', end='')  # 隐藏光标\n",
    "print('\\033[8m', end='')  # 隐藏输出(等价于禁止回显)\n",
    "print(F'\\033[{22};{38}H', end='')  # 输入位置\n",
    "input()\n",
    "print('\\033[?25h', end='')   # 显示光标\n",
    "print(restore, end='')   # 恢复文本属性\n",
    "print(clear, end='')\n",
    "print('\\033[0;0H', end='')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 思考题目"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 题目一      \n",
    "\n",
    "&emsp;&emsp;为什么下面语句能执行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "30\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(None, None)"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 20\n",
    "b = 30\n",
    "print(a), print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;但是，下面语句不能执行；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "can't assign to operator (<ipython-input-34-a1cdc1607096>, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-34-a1cdc1607096>\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m    a = a + 10, b = b + 10\u001b[0m\n\u001b[0m       ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m can't assign to operator\n"
     ]
    }
   ],
   "source": [
    "a = 20\n",
    "b = 30\n",
    "a = a + 10, b = b + 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;应该怎么修改达到同样的目的？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30 40\n"
     ]
    }
   ],
   "source": [
    "a, b = a + 10 , b + 10 \n",
    "print(a, b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 题目二\n",
    "    - 解释下如下代码产生错误的原因。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "a = 20\n",
    "a =20\n",
    "print(a.bit_length())\n",
    "b = 'hello'\n",
    "print(b.count('l'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-37-8c8bd65b37f2>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-37-8c8bd65b37f2>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m    print(20.bit_length())    # 为什么不能执行\u001b[0m\n\u001b[0m                      ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "print(20.bit_length())    # 为什么不能执行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "print('hello'.count('l'))    # 为什么能执行"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "271px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
